import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
import NProgress from "nprogress";
import router from "../router/router"
import { Message } from "element-ui";
import "nprogress/nprogress.css";
Vue.use(VueAxios, axios);

const service = axios.create({
  timeout: 300000, // request timeout
});
service.interceptors.request.use(
  (config) => {
    // NProgress.start();
    config.headers['Authorization'] = window.sessionStorage.getItem('access_token')
	// config.headers['Cookie'] = window.sessionStorage.getItem('access_token')
    config.headers['Accept'] = "*/*"
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    // console.log(response)
    // NProgress.done();
    switch (response && response.data.code) {
      case 401:
        // Message({
        //   message: "登录状态已过期，需重新登录！",
        //   type: "error",
        //   duration: 2 * 1000, // 提示时长
        // });
        window.sessionStorage.clear();
        router.replace("/login");
        break;
    //   // case 500:
    //   //   Message({
    //   //     message: response.data.message,
    //   //     type: "error",
    //   //     duration: 2 * 1000, // 提示时长
    //   //   });
    //   //   // window.sessionStorage.clear();
    //   //   // router.replace("/index");
    //   //   break;
    //   // case 404:
    //   //   Message({
    //   //     message: "网络请求错误,未找到该资源!",
    //   //     type: "error",
    //   //     duration: 2 * 1000, // 提示时长
    //   //   });
    //   //   // window.sessionStorage.clear();
    //   //   // router.replace("/index");
    //   //   break;
    }
    return Promise.resolve(response);
  },
  (error) => {
    // NProgress.done();
    switch (error.response && error.response.status) {
      case 401:
        Message({
          message: "登录状态已过期，需重新登录！",
          type: "error",
          duration: 2 * 1000, // 提示时长
        });
        window.sessionStorage.clear();
        router.replace("/login");
        break;
      case 500:
        Message({
          message: "服务器端异常，请联系管理员处理！",
          type: "error",
          duration: 2 * 1000, // 提示时长
        });
        // window.sessionStorage.clear();
        // router.replace("/index");
        break;
      case 404:
        Message({
          message: "网络请求错误,未找到该资源!",
          type: "error",
          duration: 2 * 1000, // 提示时长
        });
        // window.sessionStorage.clear();
        // router.replace("/index");
        break;
    }
    return Promise.reject(error);
  }
);

export default service;
